<template>
  <div class="base-container" id="main">
    <t-steps :current="activeForm" status="process" :onChange="onCurChanged">
      <t-step-item v-for="(item,index) in stepList" :title="item.title" :key="index" :content="isSubmit(item.id)">
      </t-step-item>
    </t-steps>
    <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium">
    </t-loading>
    <t-form :key="activeForm" :colon="true" v-if="activeForm === 0" labelAlign="top" ref="form" :data="formData0"
            :rules="rules0" class="step-form">
      <t-alert v-if="site_tag === 'jtt'" style="margin-bottom: 14px" theme="info" title="填写说明：">
        <div slot="message">
          <p class="span-title">
            一、主要内容及时间要求
          </p>
          <p class="span-txt">
            本项目执行情况报告于每年11月30日前由项目承担单位填写，并上报归口管理单位和厅科技主管部门（各一份）。内容包括：
          </p>
          <p class="span-txt">
            1、项目总体进展情况概述（包括项目总体进度、经费使用情况、本年度参加研究的全时人数等）。
          </p>
          <p class="span-txt">
            2、本报告期所开展的工作及计划执行情况。
          </p>
          <p class="span-txt">
            3、已取得的成果情况（包括中期成果，已取得专利、发表论文、建立中试线、人才培养等情况的简要描述）。
          </p>
          <p class="span-txt">
            4、组织管理经验、存在问题及建议。
          </p>
          <p class="span-txt">
            5、填报《江西省交通运输厅科技项目执行情况表》。
          </p>
          <p class="span-title">
            二、填写格式及要求
          </p>
          <p class="span-txt">
            1、项目执行情况报告要求文字简练，一般不超过3000字。
          </p>
          <p class="span-txt">
            2、涉及需保密的内容请在报告中注明密级。
          </p>
          <!--        <p class="span-txt">-->
          <!--          3、执行情况表中带“（ ）”的条目，请根据条目后所列选项，在“（ ）”内填写相应的数字。-->
          <!--        </p>-->
        </div>
      </t-alert>
      <t-alert v-else style="margin-bottom: 24px" theme="info" title="填写说明：">
        <div slot="message">
          <p class="span-title">
            一、主要内容及时间要求
          </p>
          <p class="span-txt">
            本项目执行情况报告于每年6月30日（半年度报告）、12月31日（年度报告）前由项目承担单位填写，并上报归口管理单位和集团科技主管部门。内容包括：
          </p>
          <p class="span-txt">
            1、项目总体进展情况概述（包括项目总体进度、经费使用情况、本年度参加研究的全时人数等）
          </p>
          <p class="span-txt">
            2、本报告期所开展的工作及计划执行情况。
          </p>
          <p class="span-txt">
            3、已取得的成果情况（包括中期成果，已取得专利、发表论文、建立中试线、人才培养等情况的简要描述）。
          </p>
          <p class="span-txt">
            4、组织管理经验、存在问题及建议。
          </p>
          <p class="span-txt">
            5、填报《江西省交通投资集团有限责任公司科技项目执行情况表》。
          </p>
          <p class="span-title">
            二、填写格式及要求
          </p>
          <p class="span-txt">
            1、项目执行情况报告要求文字简练，一般不超过3000字。
          </p>
          <p class="span-txt">
            2、涉及需保密的内容请在报告中注明密级。
          </p>
          <!--        <p class="span-txt">-->
          <!--          3、执行情况表中带“（ ）”的条目，请根据条目后所列选项，在“（ ）”内填写相应的数字。-->
          <!--        </p>-->
        </div>
      </t-alert>
      <div style="flex: 1;margin-bottom: 24px">
        <t-form-item name="projectId" label="项目名称">
          <template #label>
            项目名称<span style="color: red">(任务书签订之后，验收申请提交之前)</span>
          </template>
          <t-select style="width: 390px" @change="onProjectChange" clearable v-model="formData0.projectId"
                    :options="projectOptions"></t-select>
          <t-button
            @click="dialog.header=contractData.projectName;dialog.objId=formData0.projectId;dialog.open_contract_detail=true"
            v-if="formData0.projectId" variant="text" class="t-button-link">
            <t-icon name="info-circle" slot="icon"/>
            详情
          </t-button>
        </t-form-item>
        <t-form-item label="项目总体进展情况概述（包括项目总体进度、经费使用情况、本年度参加研究的全时人数等）" name="overview">
          <tiny-mce-editor v-model="formData0.overview" :key="activeForm"></tiny-mce-editor>
        </t-form-item>
      </div>
      <t-row>
        <t-col :span="11">
          <t-space :size="10">
            <t-button theme="primary" @click="onSubmit0">下一步</t-button>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <t-form :key="activeForm" :colon="true" v-if="activeForm === 1" labelAlign="top" ref="form" :data="formData1"
            :rules="rules1"
            class="step-form">
      <div style="flex: 1;margin-bottom: 24px">
        <t-form-item label="本报告期所开展的工作" name="content">
          <tiny-mce-editor v-model="formData1.content" :key="activeForm"></tiny-mce-editor>
        </t-form-item>
        <t-form-item label="计划执行情况" :show-error-message="false" name="researchPlans">
          <project-research-plan ref="project-research-plan" :projectId="projectId" :report-id="getReportId()"
                                 :edit-open="true" v-model="formData1.researchPlans"></project-research-plan>
        </t-form-item>
      </div>
      <t-row>
        <t-col :span="11">
          <t-space :size="10">
            <t-button  @click="onCurChanged(0)" theme="primary" variant="base">上一步
            </t-button>
            <t-button theme="primary" @click="onSubmit1" >下一步</t-button>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <t-form :key="activeForm" :colon="true" v-if="activeForm === 2" labelAlign="top" ref="form" :data="formData2"
            :rules="rules2"
            class="step-form">
      <div style="flex: 1;margin-bottom: 24px">
        <t-form-item label="已取得的成果情况（包括中期成果，已取得专利、发表论文、建立中试线、人才培养等情况的简要描述）" name="content">
          <tiny-mce-editor v-model="formData2.content" :key="activeForm"></tiny-mce-editor>
        </t-form-item>
        <t-form-item label="已取得的成果情况" name="projectExpectResults">
          <project-approach-expect-results ref="project-approach-expect-results" :report-id="getReportId()"
                                           v-model="formData2.projectExpectResults"
                                           :edit-open="true"></project-approach-expect-results>
        </t-form-item>
      </div>
      <t-row>
        <t-col :span="11">
          <t-space :size="10">
            <t-button  @click="onCurChanged(1)" theme="primary" variant="base">上一步
            </t-button>
            <t-button theme="primary" @click="onSubmit2" >下一步</t-button>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <t-form :key="activeForm" :colon="true" v-if="activeForm === 3" labelAlign="top" ref="form" :data="formData3"
            :rules="rules3"
            class="step-form">
      <div style="flex: 1;margin-bottom: 24px">
        <t-form-item label="组织管理经验、存在问题及建议" name="content">
          <tiny-mce-editor v-model="formData3.content" :key="activeForm"></tiny-mce-editor>
        </t-form-item>
      </div>
      <t-row>
        <t-col :span="11">
          <t-space :size="10">
            <t-button  @click="onCurChanged(2)" theme="primary" variant="base">上一步
            </t-button>
            <t-button theme="primary" @click="onSubmit3" >下一步</t-button>
          </t-space>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <t-form :key="activeForm" :colon="true" v-else-if="activeForm === 4" labelAlign="top" ref="form" :data="formData4"
            :rules="rules4"
            class="step-form table-form"
            labelWidth="140px">
      <h2 style="margin-bottom: 10px;text-align: center">{{
          site_tag === 'jtt' ? '江西省交通运输厅科技' : '江西省交通投资集团有限责任公司'
        }}项目执行情况表</h2>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>项目名称</t-col>
        <t-col :span="4">
          <t-form-item name="projectId">
            {{ contractData.projectName }}
          </t-form-item>
        </t-col>
        <t-col :span="2" class="title">项目编号</t-col>
        <t-col :span="4">
          {{ contractData.project.projectNum }}
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>报告日期</t-col>
        <t-col :span="4">
          <t-form-item name="reportDate">
            <t-date-picker v-model="formData4.reportDate" allow-input clearable></t-date-picker>
          </t-form-item>
        </t-col>
        <t-col :span="2" class="title"><span class="require">*</span>本报告期的起止时间</t-col>
        <t-col :span="4">
          <t-form-item name="dateRange">
            <t-date-range-picker v-model="formData4.dateRange" mode="month"
                                 :placeholder="['开始时间','截止时间']" allow-input clearable></t-date-range-picker>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title">承担单位</t-col>
        <t-col :span="10">{{ contractData.contractOthers.assumeDept.deptName }}</t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title">项目起止时间</t-col>
        <t-col :span="10">
          {{ contractData?.startDate?.substring(0, 4) }} 年
          {{ contractData?.startDate?.substring(5, 7) }} 月 至 {{ contractData?.completeDate?.substring(0, 4) }} 年
          {{ contractData?.completeDate?.substring(5, 7) }} 月
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>进展情况</t-col>
        <t-col :span="10">
          <t-form-item name="progress">
            <t-radio-group v-model="formData4.progress" :options="dict.type.progress"></t-radio-group>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row v-if="['3','4','5'].includes(formData4.progress)">
        <t-col :span="2" class="title"><span class="require">*</span>主要原因</t-col>
        <t-col :span="10">
          <t-form-item name="mainReason">
            <t-checkbox-group v-model="formData4.mainReason" :options="dict.type.main_reason"></t-checkbox-group>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>项目调整内容</t-col>
        <t-col :span="10">
          <t-form-item name="adjustContent">
            <t-checkbox-group v-model="formData4.adjustContent" :options="dict.type.adjust_content"></t-checkbox-group>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title">参加研究人员</t-col>
        <t-col :span="10" style="flex-direction: column">
          <t-row>
            <t-col :span="2" class="title">总数</t-col>
            <t-col :span="10">
              {{ contractData.projectTeam.totalCount }}人
            </t-col>

          </t-row>
          <t-row>
            <t-col :span="2" class="title">高级职称</t-col>
            <t-col :span="10">
              {{ contractData.projectTeam.highCount }}人
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="2" class="title">中级职称</t-col>
            <t-col :span="10">
              {{ contractData.projectTeam.middleCount }}人
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="2" class="title">初级职称</t-col>
            <t-col :span="10">
              {{ contractData.projectTeam.primaryCount }}人
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="2" class="title">其他人员</t-col>
            <t-col :span="10">
              {{ contractData.projectTeam.auxilian }}人
            </t-col>
          </t-row>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>投入研究的工作量(人月)</t-col>
        <t-col :span="4">
          <t-form-item name="workload">
            <t-input v-model="formData4.workload" clearable></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="2" class="title"><span class="require">*</span>培养人才</t-col>
        <t-col :span="4" style="flex-direction: column">
          <t-row style="border-bottom: 1px solid #ddd;">
            <t-col v-for="(item, index) in formData4.degreeList" :key="index" style="padding: 0 !important;border: 0;"
                   :span="12">
              <t-input-adornment prepend="取得" append="(学位)">
                <t-select style="width: 100px;" :key="index" v-model="item.degree"
                          :options="dict.type.degree"></t-select>
              </t-input-adornment>
              ，
              <t-input-adornment append="人">
                <t-input-number v-model="item.degreeCount" :key="index" style="width: 100px;"
                                :allowInputOverLimit="false" clearable
                                theme="normal" :min="0"></t-input-number>
              </t-input-adornment>
              <t-button @click="addDegree" v-if="index === 0" variant="text" class="t-button-link">
                <t-icon name="add" slot="icon"/>
                更多
              </t-button>
              <t-button v-else @click="delDegree(index)" theme="danger" variant="text" class="t-button-link">
                <t-icon name="delete" slot="icon"/>
                删除
              </t-button>
            </t-col>
          </t-row>
          <t-row>
            <t-col v-for="(item, index) in formData4.profTitList" :key="index" style="padding: 0 !important;border: 0;"
                   :span="12">
              <t-input-adornment prepend="取得" append="(职称)">
                <t-select style="width: 100px;" :key="index" v-model="item.profTit"
                          :options="dict.type.prof_tit"></t-select>
              </t-input-adornment>
              ，
              <t-input-adornment append="人">
                <t-input-number :key="index" v-model="item.profTitCount" style="width: 100px;"
                                :allowInputOverLimit="false" clearable
                                theme="normal" :min="0"></t-input-number>
              </t-input-adornment>
              <t-button @click="addProfTit" v-if="index === 0" variant="text" class="t-button-link">
                <t-icon name="add" slot="icon"/>
                更多
              </t-button>
              <t-button v-else @click="delProfTit(index)" theme="danger" variant="text" class="t-button-link">
                <t-icon name="delete" slot="icon"/>
                删除
              </t-button>
            </t-col>
          </t-row>
        </t-col>
      </t-row>
      <t-row style="min-height: 300px">
        <t-col :span="2" class="title"><span class="require">*</span>本报告期的主要研究工作</t-col>
        <t-col :span="10">
          <t-form-item name="mainWork">
            <tiny-mce-editor v-model="formData4.mainWork" :maxlength="maxlength"
                             :textLength.sync="lengthLimitObj.mainWork"></tiny-mce-editor>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>已取得的成果</t-col>
        <t-col :span="10" style="flex-direction: column">
          <t-row>
            <t-col :span="3" class="title">新产品、新材料、新装置、新技术、新工艺</t-col>
            <t-col :span="3">
              <t-form-item name="projectAnnualReportResults.newProductCount">
                <t-input-adornment append="项">
                  <t-input-number v-model="formData4.projectAnnualReportResults.newProductCount"
                                  :allowInputOverLimit="false" clearable
                                  theme="normal" :min="0"></t-input-number>
                </t-input-adornment>
              </t-form-item>
            </t-col>
            <t-col :span="3" class="title">论文</t-col>
            <t-col :span="3">
              <t-form-item name="projectAnnualReportResults.paperCount">
                <t-input-adornment append="篇">
                  <t-input-number v-model="formData4.projectAnnualReportResults.paperCount" :allowInputOverLimit="false"
                                  clearable
                                  theme="normal" :min="0"></t-input-number>
                </t-input-adornment>
              </t-form-item>
            </t-col>
          </t-row>

          <t-row>
            <t-col :span="3" class="title">专著</t-col>
            <t-col :span="3">
              <t-form-item name="projectAnnualReportResults.monographCount">
                <t-input-adornment append="部">
                  <t-input-number v-model="formData4.projectAnnualReportResults.monographCount"
                                  :allowInputOverLimit="false" clearable
                                  theme="normal" :min="0"></t-input-number>
                </t-input-adornment>
              </t-form-item>
            </t-col>
            <t-col :span="3" class="title">调查研究报告</t-col>
            <t-col :span="3">
              <t-form-item name="projectAnnualReportResults.researchReportCount">
                <t-input-adornment append="份">
                  <t-input-number v-model="formData4.projectAnnualReportResults.researchReportCount"
                                  :allowInputOverLimit="false" clearable
                                  theme="normal" :min="0"></t-input-number>
                </t-input-adornment>
              </t-form-item>
            </t-col>
          </t-row>

          <t-row>
            <t-col :span="3" class="title">其它成果</t-col>
            <t-col :span="9">
              <t-form-item name="projectAnnualReportResults.otherCount">
                <t-input-adornment append="项">
                  <t-input-number v-model="formData4.projectAnnualReportResults.otherCount" :allowInputOverLimit="false"
                                  clearable
                                  theme="normal" :min="0"></t-input-number>
                </t-input-adornment>
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>已获得的专利</t-col>
        <t-col :span="10" style="flex-direction: column">
          <t-row>
            <t-col :span="3" class="title">国外发明专利</t-col>
            <t-col :span="3">
              <t-form-item name="projectAnnualReportPatent.foreignCount">
                <t-input-adornment append="项">
                  <t-input-number v-model="formData4.projectAnnualReportPatent.foreignCount"
                                  :allowInputOverLimit="false"
                                  clearable
                                  theme="normal" :min="0"></t-input-number>
                </t-input-adornment>
              </t-form-item>
            </t-col>
            <t-col :span="3" class="title">国内发明专利</t-col>
            <t-col :span="3">
              <t-form-item name="projectAnnualReportPatent.homeCount">
                <t-input-adornment append="项">
                  <t-input-number v-model="formData4.projectAnnualReportPatent.homeCount" :allowInputOverLimit="false"
                                  clearable
                                  theme="normal" :min="0"></t-input-number>
                </t-input-adornment>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="3" class="title">其它专利</t-col>
            <t-col :span="9">
              <t-form-item name="projectAnnualReportPatent.otherCount">
                <t-input-adornment append="项">
                  <t-input-number v-model="formData4.projectAnnualReportPatent.otherCount" :allowInputOverLimit="false"
                                  clearable
                                  theme="normal" :min="0"></t-input-number>
                </t-input-adornment>
              </t-form-item>
            </t-col>

          </t-row>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>经费到位情况</t-col>
        <t-col :span="10" style="flex-direction: column">
          <t-row>
            <t-col :span="3" class="title">拨款总经费</t-col>
            <t-col :span="9">
              <t-form-item name="projectAnnualReportFunding.totalMoney">
                <t-input-adornment append="万元">
                  <t-input-number :decimal-places="2"
                                  @keyup="()=>{if(formData4.projectAnnualReportFunding.totalMoney){formData4.projectAnnualReportFunding.totalMoney=Number((formData4.projectAnnualReportFunding.totalMoney || 0).toString().match(/^\d+(?:\.\d{0,2})?/))}}"
                                  :allowInputOverLimit="false" clearable
                                  v-model="formData4.projectAnnualReportFunding.totalMoney"
                                  theme="normal"
                                  :min="0"></t-input-number>
                </t-input-adornment>
              </t-form-item>
            </t-col>

          </t-row>
          <t-row>
            <t-col :span="3" class="title">已拨经费</t-col>
            <t-col :span="9">
              <t-form-item name="projectAnnualReportFunding.alreadyMoney">
                <t-input-adornment append="万元">
                  <t-input-number :decimal-places="2"
                                  @keyup="()=>{if(formData4.projectAnnualReportFunding.alreadyMoney){formData4.projectAnnualReportFunding.alreadyMoney=Number((formData4.projectAnnualReportFunding.alreadyMoney || 0).toString().match(/^\d+(?:\.\d{0,2})?/))}}"
                                  :allowInputOverLimit="false" clearable
                                  v-model="formData4.projectAnnualReportFunding.alreadyMoney"
                                  theme="normal"
                                  :min="0"></t-input-number>
                </t-input-adornment>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="3" class="title">未拨经费</t-col>
            <t-col :span="9">
              <t-form-item name="projectAnnualReportFunding.notMoney">
                <t-input-adornment append="万元">
                  <t-input-number :decimal-places="2"
                                  @keyup="()=>{if(formData4.projectAnnualReportFunding.notMoney){formData4.projectAnnualReportFunding.notMoney=Number((formData4.projectAnnualReportFunding.notMoney || 0).toString().match(/^\d+(?:\.\d{0,2})?/))}}"
                                  :allowInputOverLimit="false" clearable
                                  v-model="formData4.projectAnnualReportFunding.notMoney"
                                  theme="normal"
                                  :min="0"></t-input-number>
                </t-input-adornment>
              </t-form-item>
            </t-col>

          </t-row>
          <t-row>
            <t-col :span="3" class="title">依托工程配套总经费</t-col>
            <t-col :span="9">
              <t-form-item name="projectAnnualReportFunding.dependMoney">
                <t-input-adornment append="万元">
                  <t-input-number :decimal-places="2"
                                  @keyup="()=>{if(formData4.projectAnnualReportFunding.dependMoney){formData4.projectAnnualReportFunding.dependMoney=Number((formData4.projectAnnualReportFunding.dependMoney || 0).toString().match(/^\d+(?:\.\d{0,2})?/))}}"
                                  :allowInputOverLimit="false" clearable
                                  v-model="formData4.projectAnnualReportFunding.dependMoney"
                                  theme="normal"
                                  :min="0"></t-input-number>
                </t-input-adornment>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="3" class="title">已经落实配套经费</t-col>
            <t-col :span="9">
              <t-form-item name="projectAnnualReportFunding.implementMoney">
                <t-input-adornment append="万元">
                  <t-input-number :decimal-places="2"
                                  @keyup="()=>{if(formData4.projectAnnualReportFunding.implementMoney){formData4.projectAnnualReportFunding.implementMoney=Number((formData4.projectAnnualReportFunding.implementMoney || 0).toString().match(/^\d+(?:\.\d{0,2})?/))}}"
                                  :allowInputOverLimit="false" clearable
                                  v-model="formData4.projectAnnualReportFunding.implementMoney"
                                  theme="normal"
                                  :min="0"></t-input-number>
                </t-input-adornment>
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>
      </t-row>
      <t-row style="margin-top: 24px">
        <t-col style="border: 0;margin: 0px;padding: 0px !important" :span="11" class="query-form-inline">
          <t-button theme="primary" :loading="applyLoading" @click="onSubmit4(1)">{{
              applyLoading ? '提交中...' : '暂存'
            }}
          </t-button>
          <t-tooltip content="提交后不可再编辑会进入审批流程">
            <t-button :loading="applyLoading" theme="primary" @click="onSubmit4(2)">
              {{ applyLoading ? '提交中...' : '提交到单位管理员' }}
            </t-button>
          </t-tooltip>
        </t-col>
        <t-col style="border: 0;margin: 0px;padding: 0px !important" :span="1" class="operation-container">
          <t-button variant="outline" @click="close">返回</t-button>
        </t-col>
      </t-row>
    </t-form>
    <contract-detail-dialog :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_contract_detail"
                            v-if="dialog.open_contract_detail"></contract-detail-dialog>
  </div>
</template>

<script>
import TinyMceEditor from "@/components/TinyMceEditor/index.vue";
import ContractDetailDialog from "../contract/components/contract-detail-dialog.vue";
import projectApproachExpectResults from "./components/project-approach-expectResults.vue";
import projectResearchPlan from "./components/project-research-plan.vue";


export default {
  name: "performance-report-apply",
  dicts: ['progress', 'adjust_content', 'main_reason', 'degree', 'prof_tit'],
  components: {
    TinyMceEditor,
    ContractDetailDialog,
    projectApproachExpectResults,
    projectResearchPlan
  },
  data() {
    return {
      site_tag: import.meta.env.VITE_SITE_TAG,
      taskId: null,
      projectId: null,
      reportId: null,
      dialog: {
        header: '',
        objId: null,
        open_contract_detail: false,
      },
      activeForm: 0,
      stepList: [
        {
          id: 'step0',
          title: '项目总体进展情况概述',
          require: true,
        },
        {
          id: 'step1',
          title: '本报告期所开展的工作及计划执行情况',
          require: true,
        },
        {
          id: 'step2',
          title: '已取得的成果情况',
          require: true,
        },
        {
          id: 'step3',
          title: '组织管理经验、存在问题及建议',
          require: true,
        },
        {
          id: 'step4',
          title: '项目执行情况表',
          require: false,
        },
      ],
      maxlength: 3000,
      applyLoading: false,
      projectOptions: [],
      contractData: {
        project: {},
        projectTeam: {},
        contractOthers: {
          assumeDept: {}
        }
      },
      formData0: {
        projectId: null,
        overview: '',
      },
      rules0: {
        projectId: [
          {
            required: true,
            message: "项目名称不能为空",
          },
        ],
        overview: [
          {
            required: true,
            message: "项目总体进展情况概述不能为空",
          },
        ],
      },
      formData1: {
        content: '',
        reportId: null,
        projectId: null,
        researchPlans: []
      },
      rules1: {
        content: [
          {
            required: true,
            message: "本报告期所开展的工作不能为空",
          },
        ],
        researchPlans: [{required: true, validator: (val) => val && val.length, message: "计划执行情况不能为空", type: "error"}],
      },
      formData2: {
        content: '',
        projectExpectResults: []
      },
      rules2: {
        content: [
          {
            required: true,
            message: "简要描述工作不能为空",
          },
        ],
        projectExpectResults: [{
          required: true,
          validator: (val) => val && val.length,
          message: "已取得的成果情况不能为空",
          type: "error"
        }],
      },
      formData3: {
        content: '',
      },
      rules3: {
        // content: [
        //   {
        //     required: true,
        //     message: "组织管理经验、存在问题及建议不能为空",
        //   },
        // ],
      },
      formData4: {
        dateRange: [],
        reportDate: '',
        startDate: '',
        endDate: '',
        progress: '',
        mainReason: [],
        adjustContent: [],
        workload: '',
        mainWork: '',
        projectId: null,
        projectAnnualReportPatent: {
          foreignCount: 0,
          homeCount: 0,
          otherCount: 0,
        },
        projectAnnualReportResults: {
          newProductCount: 0,
          paperCount: 0,
          monographCount: 0,
          researchReportCount: 0,
          otherCount: 0,
        },
        projectAnnualReportFunding: {
          totalMoney: 0,
          alreadyMoney: 0,
          notMoney: 0,
          dependMoney: 0,
          implementMoney: 0,
        },
        degreeList: [{
          degree: '',
          degreeCount: 0,
          sort: 1
        }],
        profTitList: [{
          profTit: '',
          profTitCount: 0,
          sort: 1
        }],
      },
      lengthLimitObj: {
        mainWork: 0
      },
      rules4: {
        // projectId: [
        //   {
        //     required: true,
        //     message: "项目名称不能为空",
        //   },
        // ],
        reportDate: [
          {
            required: true,
            message: "报告日期不能为空",
          },
        ],
        dateRange: [{required: true, validator: (val) => val && val.length, message: "本报告期的起止时间不能为空", type: "error"}],
        progress: [
          {
            required: true,
            message: "进展情况不能为空",
          },
        ],
        mainReason: [{required: true, validator: (val) => val && val.length, message: "主要原因不能为空", type: "error"}],
        adjustContent: [{required: true, validator: (val) => val && val.length, message: "项目调整内容不能为空", type: "error"}],
        workload: [
          {
            required: true,
            message: "投入研究的工作量(人月)不能为空",
          },
        ],
        mainWork: [
          {
            required: true,
            message: "本报告期的主要研究工作不能为空",
          },
        ]
      }
    }
  },
  watch: {
    activeForm: {
      immediate: true,
      handler(val) {
        const targetEle = document.getElementById("main")
        if (targetEle) {
          const {pos, top} = targetEle.style;
          targetEle.style.position = 'relative';
          targetEle.style.top = '-100px';
          targetEle.scrollIntoView({behavior: 'smooth', block: 'start', inline: "nearest"});
          targetEle.style.top = top;
          targetEle.style.position = pos;
        }
      }
    }
  },
  created() {
    const taskId = this.$route.params && this.$route.params.taskId;
    if (!taskId) {
      this.$message.error("缺少任务Id");
      this.$router.push("/kjxm/implement/performance-report-my");
      return false;
    }
    this.taskId = taskId;
    this.projectId = Number(sessionStorage.getItem(`${taskId}-performance-report-projectId`));
    const activeForm = Number(sessionStorage.getItem(`${taskId}-performance-report-activeForm`)) || 0;
    this.onCurChanged(activeForm)
    this.getProjectList();
  },
  methods: {
    getReportId() {
      return sessionStorage.getItem(`${this.taskId}-performance-report-step0`);
    },
    isSubmit(name) {
      return sessionStorage.getItem(`${this.taskId}-performance-report-${name}`) ? '已提交' : '未提交';
    },
    onCurChanged(cur, pre) {
      if (Number(cur) !== 0) {
        if (!sessionStorage.getItem(`${this.taskId}-performance-report-step0`)) {
          this.applyLoading = false;
          this.$message.error("项目总体进展情况概述还未提交")
          return false;
        }
      }
      if (!this.applyLoading) {
        this.applyLoading = true;
      }
      // 根据不同的activeForm 复查数据
      if (Number(cur) === 0) {
        if (sessionStorage.getItem(`${this.taskId}-performance-report-step0`)) {
          const objId = Number(sessionStorage.getItem(`${this.taskId}-performance-report-step0`));
          this.$api.kjxm.implement.performanceReportGet(objId).then(response => {
            if (response.data) {
              Object.assign(this.formData0, response.data)
            }
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-performance-report-activeForm`, cur);
            this.applyLoading = false;
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-performance-report-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 1) {
        if (sessionStorage.getItem(`${this.taskId}-performance-report-step0`)) {
          const objId = Number(sessionStorage.getItem(`${this.taskId}-performance-report-step0`));
          this.$api.kjxm.implement.performanceReportPlanGetByReportId(objId).then(response => {
            if (response.data) {
              Object.assign(this.formData1, response.data)
            }
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-performance-report-activeForm`, cur);
            this.applyLoading = false;
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}--performance-report-activeForm`, cur);
          this.applyLoading = false;
        }

      } else if (Number(cur) === 2) {
        if (sessionStorage.getItem(`${this.taskId}-performance-report-step0`)) {
          const objId = Number(sessionStorage.getItem(`${this.taskId}-performance-report-step0`));
          this.$api.kjxm.implement.performanceReportResultsGetByReportId(objId).then(response => {
            if (response.data) {
              Object.assign(this.formData2, response.data)
            }
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-performance-report-activeForm`, cur);
            this.applyLoading = false;
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-performance-report-activeForm`, cur);
          this.applyLoading = false;
        }

      } else if (Number(cur) === 3) {
        if (sessionStorage.getItem(`${this.taskId}-performance-report-step0`)) {
          const objId = Number(sessionStorage.getItem(`${this.taskId}-performance-report-step0`));
          this.$api.kjxm.implement.performanceReportExperienceGetByReportId(objId).then(response => {
            if (response.data) {
              Object.assign(this.formData3, response.data)
            }
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-performance-report-activeForm`, cur);
            this.applyLoading = false;
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-performance-report-activeForm`, cur);
          this.applyLoading = false;
        }

      } else if (Number(cur) === 4) {
        this.$api.kjxm.contract.getAll(this.projectId).then(response => {
          this.contractData = response.data;
          if (sessionStorage.getItem(`${this.taskId}-performance-report-step0`)) {
            const objId = Number(sessionStorage.getItem(`${this.taskId}-performance-report-step0`));
            this.$api.kjxm.implement.performanceReportTableGetByReportId(objId).then(response => {
              if (response.data) {
                response.data.mainReason = response.data.mainReason.split(",").filter(item=> item !== '') || [];
                response.data.adjustContent = response.data.adjustContent.split(",").filter(item=> item !== '') || [];

                Object.assign(this.formData4, response.data)
                this.formData4.dateRange = [response.data.startDate, response.data.endDate]
                if (this.formData4.degreeList.length <= 0) {
                  this.formData4.degreeList = [{
                    degree: '',
                    degreeCount: 0,
                    sort: 1
                  }]
                }
                if (this.formData4.profTitList.length <= 0) {
                  this.formData4.profTitList = [{
                    profTit: '',
                    profTitCount: 0,
                    sort: 1
                  }]
                }
              }
              this.activeForm = cur;
              sessionStorage.setItem(`${this.taskId}-performance-report-activeForm`, cur);
              this.applyLoading = false;
            }).catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
          } else {
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-performance-report-activeForm`, cur);
            this.applyLoading = false;
          }
        }).catch((e) => {
          this.applyLoading = false;
          this.$message.error(e.toString());
        });
      } else {
        this.activeForm = cur;
        sessionStorage.setItem(`${this.taskId}-performance-report-activeForm`, cur);
        this.applyLoading = false;
      }
    },
    addDegree() {
      this.formData4.degreeList.push({
        degree: '',
        degreeCount: 0,
        sort: 1
      });
    },
    delDegree(index) {
      this.formData4.degreeList.splice(index, 1);
    },
    addProfTit() {
      this.formData4.profTitList.push({
        profTit: '',
        profTitCount: 0,
        sort: 1
      });
    },
    delProfTit(index) {
      this.formData4.profTitList.splice(index, 1);
    },
    getProjectList() {
      this.$api.kjxm.implement.changeApplyMyProjectList().then(response => {
        this.projectOptions = response.data.map(val => {
          return {
            label: val.projectName,
            value: val.id,
            contractId: val.contractId,
            ...val,
          }
        });
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onProjectChange(val, content) {
      this.projectId = val;
      sessionStorage.setItem(`${this.taskId}-performance-report-projectId`, val);
    },
    onSubmit0() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.applyLoading = true;
          // 判断是否提交过
          if (sessionStorage.getItem(`${this.taskId}-performance-report-step0`)) {
            this.$api.kjxm.implement.performanceReportUpdate(this.formData0).then(response => {
              this.$message.success("提交成功")
              this.onCurChanged(1);
            }).catch(e => {
              this.applyLoading = false;
              this.$message.error(e.toString())
            })
          } else {
            this.$api.kjxm.implement.performanceReportAdd(this.formData0).then(response => {
              this.$message.success("提交成功")
              sessionStorage.setItem(`${this.taskId}-performance-report-step0`, response.data.id);
              this.onCurChanged(1);
            }).catch(e => {
              this.applyLoading = false;
              this.$message.error(e.toString())
            })
          }

        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    onSubmit1() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          const isValidate = this.$refs["project-research-plan"].checkData()
          if (!isValidate) {
            return false;
          }
          this.applyLoading = true;
          // 判断是否提交过
          if (sessionStorage.getItem(`${this.taskId}-performance-report-step1`)) {
            this.$api.kjxm.implement.performanceReportPlanUpdate({
              ...this.formData1,
              projectId: this.projectId,
              reportId: sessionStorage.getItem(`${this.taskId}-performance-report-step0`),
            }).then(response => {
              this.$message.success("提交成功")
              this.onCurChanged(2);
            }).catch(e => {
              this.applyLoading = false;
              this.$message.error(e.toString())
            })
          } else {
            this.$api.kjxm.implement.performanceReportPlanAdd({
              ...this.formData1,
              projectId: this.projectId,
              reportId: sessionStorage.getItem(`${this.taskId}-performance-report-step0`),
            }).then(response => {
              this.$message.success("提交成功")
              sessionStorage.setItem(`${this.taskId}-performance-report-step1`, response.data.id);
              this.onCurChanged(2);
            }).catch(e => {
              this.applyLoading = false;
              this.$message.error(e.toString())
            })
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    onSubmit2() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          const isValidate = this.$refs["project-approach-expect-results"].checkData()
          if (!isValidate) {
            return false;
          }
          this.applyLoading = true;
          // 判断是否提交过
          if (sessionStorage.getItem(`${this.taskId}-performance-report-step2`)) {
            this.$api.kjxm.implement.performanceReportResultsUpdate({
              ...this.formData2,
              projectId: this.projectId,
              reportId: sessionStorage.getItem(`${this.taskId}-performance-report-step0`),
            }).then(response => {
              this.$message.success("提交成功")
              this.onCurChanged(3);
            }).catch(e => {
              this.applyLoading = false;
              this.$message.error(e.toString())
            })
          } else {
            this.$api.kjxm.implement.performanceReportResultsAdd({
              ...this.formData2,
              projectId: this.projectId,
              reportId: sessionStorage.getItem(`${this.taskId}-performance-report-step0`),
            }).then(response => {
              this.$message.success("提交成功")
              sessionStorage.setItem(`${this.taskId}-performance-report-step2`, response.data.id);
              this.onCurChanged(3);
            }).catch(e => {
              this.applyLoading = false;
              this.$message.error(e.toString())
            })
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    onSubmit3() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.applyLoading = true;
          // 判断是否提交过
          if (sessionStorage.getItem(`${this.taskId}-performance-report-step3`)) {
            this.$api.kjxm.implement.performanceReportExperienceUpdate({
              ...this.formData3,
              projectId: this.projectId,
              reportId: sessionStorage.getItem(`${this.taskId}-performance-report-step0`),
            }).then(response => {
              this.$message.success("提交成功")
              this.onCurChanged(4);
            }).catch(e => {
              this.applyLoading = false;
              this.$message.error(e.toString())
            })
          } else {
            this.$api.kjxm.implement.performanceReportExperienceAdd({
              ...this.formData3,
              projectId: this.projectId,
              reportId: sessionStorage.getItem(`${this.taskId}-performance-report-step0`),
            }).then(response => {
              this.$message.success("提交成功")
              sessionStorage.setItem(`${this.taskId}-performance-report-step3`, response.data.id);
              this.onCurChanged(4);
            }).catch(e => {
              this.applyLoading = false;
              this.$message.error(e.toString())
            })
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    onSubmit4(type) {
      const [startDate, endDate] = this.formData4.dateRange;
      if (type === 1) {
        this.$refs.form.validate({
          fields: ['projectId']
        }).then((validateResult) => {
          if (validateResult === true) {
            this.applyLoading = true;
            if (sessionStorage.getItem(`${this.taskId}-performance-report-step4`)) {
              this.$api.kjxm.implement.performanceReportTableUpdate({
                ...this.formData4,
                mainReason: this.formData4.mainReason.join(","),
                adjustContent: this.formData4.adjustContent.join(","),
                degreeList: this.formData4.degreeList.map((val, index) => ({...val, sort: index + 1})),
                profTitList: this.formData4.profTitList.map((val, index) => ({...val, sort: index + 1})),
                startDate,
                endDate,
                projectId: this.projectId,
                reportId: sessionStorage.getItem(`${this.taskId}-performance-report-step0`),
              }).then(response => {
                this.applyLoading = false;
                this.$message.success('暂存成功');

              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            } else {
              this.$api.kjxm.implement.performanceReportTableAdd({
                ...this.formData4,
                mainReason: this.formData4.mainReason.join(","),
                adjustContent: this.formData4.adjustContent.join(","),
                degreeList: this.formData4.degreeList.map((val, index) => ({...val, sort: index + 1})),
                profTitList: this.formData4.profTitList.map((val, index) => ({...val, sort: index + 1})),
                startDate,
                endDate,
                projectId: this.projectId,
                reportId: sessionStorage.getItem(`${this.taskId}-performance-report-step0`),
              }).then(response => {
                sessionStorage.setItem(`${this.taskId}-performance-report-step4`, response.data.id)
                this.formData4.id = response.data.id;
                this.applyLoading = false;
                this.$message.success('暂存成功');
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            }
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        })

      } else {
        this.$refs.form.validate().then((validateResult) => {
          if (validateResult === true) {
            if (this.lengthLimitObj.mainWork > this.maxlength) {
              this.$message.error(`本报告期的主要研究工作 当前字数${this.lengthLimitObj.mainWork}，限制字数${this.maxlength}`)
              return false;
            }
            // 判断培养人才
            const isValidate = this.formData4.degreeList.every((val, index) => {
              if (!val.degree) {
                this.$message.error(`培养人才：第${index + 1}条"取得学位"不能为空`);
                return false;
              }
              return true;
            });
            if (!isValidate) {
              return false;
            }
            const isValidate2 = this.formData4.profTitList.every((val, index) => {
              if (!val.profTit) {
                this.$message.error(`培养人才：第${index + 1}条"取得职称"不能为空`);
                return false;
              }
              return true;
            });
            if (!isValidate2) {
              return false;
            }
            this.stepList.forEach((val)=>{
              if (!sessionStorage.getItem(`${this.taskId}-performance-report-${val.id}`) && val.require) {
                this.$message.error(`${val.title}还未提交`)
                this.applyLoading = false;
                return false;
              }
            })
            this.applyLoading = true;
            if (sessionStorage.getItem(`${this.taskId}-performance-report-step4`)) {
              this.$api.kjxm.implement.performanceReportTableUpdate({
                ...this.formData4,
                mainReason: this.formData4.mainReason.join(","),
                adjustContent: this.formData4.adjustContent.join(","),
                degreeList: this.formData4.degreeList.map((val, index) => ({...val, sort: index + 1})),
                profTitList: this.formData4.profTitList.map((val, index) => ({...val, sort: index + 1})),
                startDate,
                endDate,
                projectId: this.projectId,
                reportId: sessionStorage.getItem(`${this.taskId}-performance-report-step0`),
              }).then(response => {
                this.$api.kjxm.implement.performanceReportSubmit({
                  projectId: this.projectId,
                  id: sessionStorage.getItem(`${this.taskId}-performance-report-step0`),
                }).then(response => {
                  this.applyLoading = false;
                  this.$message.success('提交成功');
                  this.close();
                }).catch((e) => {
                  this.applyLoading = false;
                  this.$message.error(e.toString());
                });
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            } else {
              this.$api.kjxm.implement.performanceReportTableAdd({
                ...this.formData4,
                mainReason: this.formData4.mainReason.join(","),
                adjustContent: this.formData4.adjustContent.join(","),
                degreeList: this.formData4.degreeList.map((val, index) => ({...val, sort: index + 1})),
                profTitList: this.formData4.profTitList.map((val, index) => ({...val, sort: index + 1})),
                startDate,
                endDate,
                projectId: this.projectId,
                reportId: sessionStorage.getItem(`${this.taskId}-performance-report-step0`),
              }).then(response => {
                sessionStorage.setItem(`${this.taskId}-performance-report-step4`, response.data.id)
                this.formData4.id = response.data.id;
                this.$api.kjxm.implement.performanceReportSubmit({
                  projectId: this.projectId,
                  id: sessionStorage.getItem(`${this.taskId}-performance-report-step0`),
                }).then(response => {
                  this.applyLoading = false;
                  this.$message.success('提交成功');
                  this.close();
                }).catch((e) => {
                  this.applyLoading = false;
                  this.$message.error(e.toString());
                });
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            }
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        });
      }

    },
    close() {
      this.$tab.closeOpenPage({path: "/kjxm/implement/performance-report-my"});
    }
  }
}
</script>

<style lang="less" scoped>
.base-container {
  display: flex;
  flex-direction: column;
}

.step-form {
  padding: 0 24px;
  height: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
}

//.t-row {
//  margin-bottom: 14px;
//}

.span-title {
  font-weight: bold;
}

.span-sub-txt {
  margin-left: 20px;
}

.table-form {
  /deep/ .t-radio.t-is-disabled .t-radio__label {
    color: unset
  }

  /deep/ .t-is-error .t-input__extra {
    position: static;
  }

  /deep/ .t-form__label {
    display: none;
  }

  .t-form__item {
    width: 100%;
  }

  .t-row {
    align-items: stretch;
    margin-bottom: 0px;

    .require {
      color: red;
      margin-right: 3px;
    }

    .t-col {
      border: 1px solid #ddd;
      color: #333;
      min-height: 37px;
      padding: 4px !important;
      //overflow: hidden;
      display: flex;
      align-items: center;
      margin: 0px -1px -1px 0px;

      .t-row {
        width: 100%;
      }
    }

    .title {
      background-color: #FAFAFA;
      justify-content: center;
      margin: 0px -1px -1px 0px;
      color: #000000;
      font-size: 16px;
      font-family: '宋体', serif;
      font-weight: bold;
    }
  }
}
</style>
